var path = require('path');
var glob = require('glob');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');

var entrys = getEntry();
var config = {
	context:__dirname,//entry point的文件基础路径
	//p和loader的区别在于,插件是一个纵观全局的功能,loader是针对一类文件操作的.
	plugins:getPlug(),
	/**
	entry: {
        page1: "./page1",
        page2: ["./entry1", "./entry2"]
    },
    **/
    //可用的replace value
    // [hash] compilation hash,编译hash,全局一个.
    //[chunkhash] chunk hash,为输出文件hash
    //[name] entrys的key
    //[id] entrys的id
	entry: entrys,
	/**
	通过hash,和publicPath做缓存和cdn的路径.
	output: {
    	path: "/home/proj/cdn/assets/[hash]",
    	publicPath: "http://cdn.example.com/assets/[hash]/"
	}
	**/
	output:{
		//要使用absolute path
		//文件输出路径
		//当使用webpack-dev-sever的时候,打包后的文件在内存中存储,不会输出到path
		path:path.join(__dirname,'dist'),
		//可以用[hash],让输出文件追加hash
		filename: "[name].js",
		//用来指定在浏览器中引用的public path,有<script>和<link>等
		//loader在嵌入这些引用的使用用到改路径.
		publicPath:"/webpack/dist",
		//https://segmentfault.com/q/1010000003850413,
		// chunkFilename:"[hash].[id].js"
		//在require中,注释路径.
		pathinfo:true
	},
	module:{
		preLoaders:getPreLoader(),
		loaders:getLoader(),
		noParse:[]
	},
	resolve:{
		root:path.join(__dirname,''),
		extensions:['','.js','.css'],
		alias:{
			'content.js':path.join(__dirname,'src/ut/content.js')
			//用来别名方便require,不用谢长路径
		}
	}
};

function getPreLoader(){
	return [
		{
			test:/\.(js|jsx)$/,
			exclude:/node_modules/,
			loader:'eslint-loader'
		}
	];
}

function getLoader(){
	var loader = [
			{
				test:/\.css$/,
				exclude:[''],
				loader:"style!css"
			},
			{
				test:/\.js$/,
				exclude:['/node_modules/'],
				loader:"jsx-loader?harmony"
			},
			{
				test:/\.scss$/,
				loader:"style!css!sass?sourceMap"
			},
			{
				test:/\.(png|jpg)$/,
				loader:"url-loader?limit=8192"
			}
		];
	return loader;
}
function getPlug(){
	var commonsPlugin = new webpack.optimize.CommonsChunkPlugin({
		name:'common',
		chunks:Object.keys(entrys),
		minChunks:Object.keys(entrys).length
	});
	var plugins = [commonsPlugin];
	//读取每个文件夹下的入口文件.
	var page = Object.keys(find('src/**/index.html', 'src/'));
	page.forEach(function(pathname) {
	 var conf = {
	 		//指定文件的输入
	        filename: './' + pathname + '.html',
	        //指定入口文件的模板文件
	        //支持loader,可以使用其他loader的输出(html!./index.html)
	        template: 'src/' + pathname + '.html', //html模板路径
	        inject: true,    //js插入的位置，true/'head'/'body'/false
	    };
	    console.log(pathname);
	    if (pathname in entrys) {
	        conf.inject = 'body';
	        conf.chunks = ['common',pathname];//指定要嵌入的,这里设置每个文件夹下的index.js为入口文件,index.html为入口.
	        //插入的时候url中加入unique webpack compilation hash,如果修改了源文件,编译后的hash值会修改.
	        conf.hash = true;
	    }
	    plugins.push(new HtmlWebpackPlugin(conf));
	});
	return plugins;
}
function getEntry(){
	//读取入口js,规定入口js格式.
	var entrys = {};
	var page = Object.keys(find('src/**/index.js', 'src/'));
	page.forEach(function(p){
		entrys[p]=path.join('./src',p+'.js')
	});
	return entrys;
}
function find(globPath, pathDir) {
    var files = glob.sync(globPath);
    var entries = {},
        entry, dirname, basename, pathname, extname;

    for (var i = 0; i < files.length; i++) {
        entry = files[i];
        dirname = path.dirname(entry);
        extname = path.extname(entry);
        basename = path.basename(entry, extname);
        pathname = path.join(dirname, basename);
        pathname = pathDir ? pathname.replace(new RegExp('^' + pathDir), '') : pathname;
        entries[pathname] = ['./' + entry];
    }
    return entries;
}

//用来对多个入口文件相同模块进行提取复用.
module.exports = config;